// websocket.js
const WebSocket = require("ws");

module.exports = (server, authenticateJWT) => {
  const wss = new WebSocket.Server({ noServer: true });

  // 存储连接的客户端及其对应的用户信息
  const clients = new Map();

  // 定义客服账号的用户 ID
  const customerServiceUserId = "kefu"; // 替换为实际的客服账号 ID

  // 处理WebSocket连接
  wss.on("connection", (ws, req) => {
    console.log("WebSocket connection established");
    console.log("======>", req.auth.userId);
    const userId = req.auth.userId; // 假设在JWT验证中间件中已经将userId附加到req对象上

    // 将客户端添加到clients map中
    clients.set(userId, ws);
    console.log(`Client ${userId} connected`); // 添加日志

    // 处理消息接收
    ws.on("message", (message) => {
      console.log(`Received message from ${userId}: ${message}`);
      const data = JSON.parse(message);
      const { content, to } = data;

      if (userId === customerServiceUserId) {
        // 如果是客服账号发送的消息，找到接收者并发送消息
        console.log(`Customer service sending message to ${to}`); // 添加日志
        const recipient = clients.get(to);
        if (recipient) {
          recipient.send(JSON.stringify({ from: userId, content }));
          console.log(`Message sent to ${to}: ${content}`);
        } else {
          ws.send(JSON.stringify({ error: "接收者不在线" }));
          console.log(`Error: Receiver ${to} is not online`);
        }
      } else {
        // 如果是客户端发送的消息，发送给客服账号
        const recipient = clients.get(customerServiceUserId);
        if (recipient) {
          recipient.send(JSON.stringify({ from: userId, content }));
          console.log(`Message sent to customer service: ${content}`);
        } else {
          ws.send(JSON.stringify({ error: "客服不在线" }));
          console.log(`Error: Customer service is not online`);
        }
      }
    });

    // 处理连接关闭
    ws.on("close", () => {
      console.log(`Client ${userId} disconnected`); // 添加日志
      clients.delete(userId);
    });
  });

  // 将HTTP服务器升级为WebSocket连接
  server.on("upgrade", (request, socket, head) => {
    console.log("Upgrade request received");

    // 打印请求头中的 Authorization 字段
    console.log("Request headers:", request.headers);
    console.log("Authorization header:", request.headers.authorization);

    // 验证JWT
    authenticateJWT(request, {}, (err) => {
      if (err) {
        console.error("JWT authentication failed:", err);
        socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
        socket.destroy();
        return;
      }

      // 将userId附加到request对象上
      request.userId = request.auth.sub; // 假设JWT的payload中包含sub字段作为userId
      console.log(`JWT authentication successful, userId: ${request.userId}`);

      wss.handleUpgrade(request, socket, head, (ws) => {
        console.log("WebSocket upgrade successful");
        wss.emit("connection", ws, request);
      });
    });
  });
};
